<script lang="ts" setup>
import { ElForm, ElMessage } from 'element-plus'
import { computed, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ResponseResult } from '#/result'

interface Props {
  options: crudTable.OptionsType
  data: any
  rules?: {
    [key: string]: any
  }
  pageOption?: crudTable.PageOption
}

type FormInstance = InstanceType<typeof ElForm>
const ruleFormRef = ref<FormInstance>()

const { options } = withDefaults(defineProps<Props>(), {
  // 默认值如果是引用类型需要使用函数返回
  pageOption: () => ({
    currentPage: 1,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100, 200],
    total: 200,
    isSmall: false,
    isHasBackground: true,
  }),
})
const emits = defineEmits(['editor', 'remove', 'submit', 'sizeChange', 'currentChange', 'sortChange', 'searchChange'])

const form = ref<{ [key: string]: any }>({})
const dialogFormVisible = ref(false)
const search = ref('')

// 过滤不需要展示的列
const columns = computed(() => {
  return options.columns.filter(item => !item.column)
})

// 编辑
const editor = (id: string) => {
  emits('editor', id, (result: any) => {
    form.value = result
  })
  dialogFormVisible.value = true
}
// 取消
const cancelEditor = () => {
  dialogFormVisible.value = false
  ElMessage('已取消')
}
// 提交
const submit = () => {
  ruleFormRef.value?.validate(async valid => {
    if (!valid) return false
    emits('submit', form.value)
    dialogFormVisible.value = false
  })
}
// 删除
const remove = (id: string) => {
  emits('remove', id)
}
// 添加
const add = () => {
  if (form.value) {
    form.value = {}
  }
  dialogFormVisible.value = true
}
// 切换当前页
const handleCurrentChange = (currentPage: number) => {
  emits('currentChange', currentPage)
}
// 切换页数量
const handleSizeChange = (currentSize: number) => {
  emits('sizeChange', currentSize)
}
// 排序
const handlerSortChange = (sort: crudTable.SortInstance) => {
  emits('sortChange', sort)
}
// 搜索
const handleSearchChange = () => {
  emits('searchChange', search.value)
}
// 名称
const title = computed(() => {
  return options.columns.find(prop => prop.search)
})
// 上传文件字段
const uploadField = computed(() => {
  return options.columns.find(prop => prop.upload)
})
// 上传图片
const handleAvatarSuccess = (res: ResponseResult<{ url: string }>) => {
  form.value[uploadField.value!.prop] = res.data!.url
  ElMessage.success({
    message: '上传文件成功!',
    showClose: true,
  })
}
</script>

<template>
  <h2 style="font-size: 20px; margin-bottom: 20px">{{ options.title }}</h2>
  <div class="search">
    <el-input v-model="search" :placeholder="`请输入${title?.label || '内容'}`" clearable @blur="handleSearchChange"></el-input>
    <el-button size="default" style="margin-bottom: 10px" type="primary" @click="add">添加{{ options.title.slice(0, 2) }} </el-button>
  </div>

  <el-table :data="data" :default-sort="pageOption.sort ?? null" border style="width: 100%" @sort-change="handlerSortChange">
    <template #empty>
      <div>
        <el-empty description="暂无数据"></el-empty>
      </div>
    </template>
    <el-table-column
      v-for="(c, index) of columns"
      :key="index"
      :label="c.label"
      :prop="c.prop"
      :sortable="pageOption.sort && c.prop === pageOption.sort.prop"
      align="center"
    >
      <template v-if="c.upload" #default="{ row }">
        <div>
          <video v-if="row.file" :src="row.file" class="video-small"></video>
          <img v-else-if="row[c.prop]" :src="row[c.prop]" alt="" style="width: 50px; height: 50px" />
        </div>
      </template>
      <!-- todo -->
      <template v-else-if="c.prop === 'course'" #default="{ row }">
        <div>
          <span>{{ row.course.name }}</span>
        </div>
      </template>
      <template v-else-if="c.prop === 'parent'" #default="{ row }">
        <div>
          <span>{{ row.parent?.name }}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column #default="{ row }" align="center" label="操作">
      <el-button size="small" type="primary" @click="editor(row._id)">编辑</el-button>
      <el-button size="small" type="danger" @click="remove(row._id)">删除</el-button>
    </el-table-column>
  </el-table>
  <!-- editor dialog  -->
  <el-dialog v-model="dialogFormVisible" :title="options.title">
    <el-form ref="ruleFormRef" :model="form" :rules="rules">
      <template v-for="(c, index) of options.columns" :key="index">
        <el-form-item v-if="c.prop !== '_id'" :label="c.label" :prop="c.prop">
          <!-- upload -->
          <el-upload
            v-if="c.upload && c.uploadUrl"
            :action="c.uploadUrl"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            class="avatar-uploader"
          >
            <!-- img -->
            <img v-if="form[c.prop] && !c.video" :src="form[c.prop]" alt="..." class="avatar" />
            <video v-else-if="c.video" :src="form[c.prop]" class="video"></video>
            <el-icon v-else class="avatar-uploader-icon">
              <plus />
            </el-icon>
            <!-- img end -->
          </el-upload>
          <!-- upload end -->
          <!-- select -->
          <el-select
            v-else-if="c.select && c.selectData"
            v-model="form[c.prop]"
            :multiple="c.multiple"
            :multiple-limit="c.multipleMax"
            :placeholder="`请选择${c.label}`"
          >
            <el-option v-for="item in c.selectData" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <!-- select end -->
          <el-input v-else v-model="form[c.prop]" :placeholder="`请输入${c.label}`" autocomplete="off"></el-input>
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <span class="编辑">
        <el-button @click="cancelEditor">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- editor dialog end -->

  <!-- pagination -->
  <div v-if="pageOption" class="pagination">
    <el-pagination
      v-model:currentPage="pageOption.currentPage"
      v-model:page-size="pageOption.pageSize"
      :background="pageOption.isHasBackground"
      :page-sizes="pageOption.pageSizes"
      :small="pageOption.isSmall"
      :total="pageOption.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
    <!-- pagination end -->
  </div>
</template>

<style lang="scss" scoped>
.search {
  margin-bottom: 10px;
  display: flex;
  width: 400px;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
